﻿<DemoPageSectionComponent Id="Editors-TagBox-Validation" ShowSizeMode="true">
    <ChildContentWithParameters Context="Params">
        @using System.ComponentModel.DataAnnotations


        <EditForm Model="@recipients" class="cw-480">

            <DataAnnotationsValidator />

            <div class="mb-4">
                <label class="demo-text mb-1"
                       for="cbxEmails">
                    Recipients:
                </label>
                <DxTagBox InputId="cbxEmails"
                          Data="@Emails.DataSource"
                          NullText="Select email recipients"
                          AllowCustomTags="true"
                          ValidateBy="TagBoxValidateBy.Tags"
                          @bind-Tags="@recipients.Data"
                          TData="string"
                          TValue="string"
                          SizeMode="Params.SizeMode"
                          CssClass="cw-480"
                          ShowValidationIcon="true" />
                <ValidationMessage For="@(() => recipients.Data)" />
            </div>

            <DxButton SubmitFormOnClick="true"
                      Text="Submit"
                      RenderStyle="ButtonRenderStyle.Secondary" />
        </EditForm>
    </ChildContentWithParameters>

    @code {
        EmailRecipients recipients = new EmailRecipients();

        [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
        public class EmailAdressesAttribute : ValidationAttribute {
            public override bool IsValid(object value) {
                IEnumerable<string> data = value as IEnumerable<string>;
                if(data != null && data.Any()) {
                    foreach (var item in data) {
                        int index = item.IndexOf('@');
                        if(index < 0 || !item.Substring(index).Contains("."))
                            return false;
                    }
                    return true;
                }
                else
                    return false;
            }

        }

        public class EmailRecipients {
            [EmailAdresses(ErrorMessage = "Invalid email")]
            public IEnumerable<string> Data { get; set; } = null;
        }
    }
</DemoPageSectionComponent>
